package com.gaojiawei.multiThread18_CompletableFutureTask;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * exception 只有前面执行业务的方法出错了，exptionnal里的内容才会执行。
 * exception 只能捕获异常的信息
 * thenCompose 既能拿到返回结果又能捕获异常信息。
 * handle 详细见笔记
 */
public class L08_ExceptionalThenComposeHandle {
    public static void main(String[] args) {
        testExceptional();
    }

    public static void testExceptional(){
        CompletableFuture<String> taskC = CompletableFuture.supplyAsync(()->{
            System.out.println("begin a");
            System.out.println(1/0);
            System.out.println("finish a");
            return "a task is ok";
        }).applyToEither(CompletableFuture.supplyAsync(()->{
            System.out.println("begin b");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            System.out.println("finish b");
            return "b task is ok";
        }),resFirst->{
            System.out.println("begin c");

            System.out.println("finish c");

            return resFirst;
        })
                .exceptionally(ex ->{
            System.out.println(ex.getMessage());
            return "任务出错了";
        });


        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(taskC.join());
    }
}
